import { getStorageSync, setStorageSync, removeStorageSync, clearStorageSync } from "@tarojs/taro";
enum DefaultValidTime {
  DefaultTime = 'forever',
  __expiryTime__ = '__expiryTime__'
}
export class UtilStorage implements StorageClass {
  set<T>(key: Key, value: T, validTime: ValidTime = DefaultValidTime.DefaultTime) {
    let expiryTime = validTime
    if (typeof validTime === 'number' && validTime > 0) {
      expiryTime = new Date().getTime() + validTime
    }
    let data:StorageData<T> = {
      value,
      [DefaultValidTime.__expiryTime__]: expiryTime
    }
    setStorageSync(key, JSON.stringify(data))
  }
  getValue<T>(key: Key): ValueData<T> {
    let res: Data<T> = this.get(key);
    return res.value;
  }
  get<T>(key: Key): Data<T> {
    const result = getStorageSync(key)
    if (result) {
      const data:StorageData<T> = JSON.parse(result)
      const expiryTime = data[DefaultValidTime.__expiryTime__]
      if (
        expiryTime === DefaultValidTime.DefaultTime ||
        (typeof expiryTime === 'number' && expiryTime > +new Date())
      ) {
        return {
          msg: 'success',
          value: data.value
        }
      }
      this.remove(key)
      return {
        msg: key + ' has expired.',
        value: null
      }
    } else {
      return {
        msg: `${key} not found in storage.`,
        value: null
      }
    }
  }
  remove(key: Key) {
    removeStorageSync(key)
  }
  clear() {
    clearStorageSync()
  }
}
